const db = require('../config/mysql');
const codeGenerator = require('../services/codeGenerator');
const cache = require('../services/cache');

class LinkController {

    /**
        * 创建短链接
        * @param {string} originalUrl - 原始长URL
        * @returns {Promise<string>} 短码
    */
    async createShortLink(originalUrl, req) {
        const connection = await db.getConnection();

        try {
            await connection.beginTransaction();

            // 1. 检查是否已存在相同URL
            const [existing] = await connection.query(
                'SELECT short_code FROM short_links WHERE original_url = ? LIMIT 1',
                [originalUrl]
            );

            if (existing.length > 0) {
                return existing[0].short_code;
            }

            // 2. 生成唯一短码
            const shortCode = await codeGenerator.generateUniqueShortCode(connection);

            // 3. 插入新记录
            await connection.query(
                'INSERT INTO short_links (short_code, original_url, user_ip) VALUES (?, ?, ?)',
                [shortCode, originalUrl, req.ip]
            );

            await connection.commit();
            return shortCode;
        } catch (error) {
            await connection.rollback();
            throw error;
        } finally {
            connection.release();
        }
    }

    /**
     * 根据短码获取原始URL
     * @param {string} shortCode - 短码
     * @returns {Promise<string|null>} 原始URL或null(如果不存在)
     */
    async getOriginalUrl(shortCode) {
        // 1. 先检查缓存
        const cachedUrl = await cache.get(shortCode);
        if (cachedUrl) {
            return cachedUrl;
        }

        // 2. 查询数据库
        const [rows] = await db.query(
            'SELECT original_url FROM short_links WHERE short_code = ? AND is_active = 1',
            [shortCode]
        );

        if (rows.length === 0) {
            return null;
        }

        // 3. 写入缓存
        await cache.set(shortCode, rows[0].original_url);
        return rows[0].original_url;
    }

    /**
     * 增加短链接点击计数
     * @param {string} shortCode - 短码
     * @returns {Promise<void>}
     */
    async incrementClickCount(shortCode) {
        try {
            await db.query(
                'UPDATE short_links SET clicks = clicks + 1 WHERE short_code = ?',
                [shortCode]
            );
        } catch (error) {
            console.error('Error incrementing click count:', error);
            // 点击统计不是关键功能，出错不影响主流程
        }
    }

    /**
     * 检查短码是否已存在
     * @param {string} shortCode - 要检查的短码
     * @returns {Promise<boolean>} 是否已存在
     */
    async checkCodeExists(shortCode) {
        const [rows] = await db.query(
            'SELECT 1 FROM short_links WHERE short_code = ? LIMIT 1',
            [shortCode]
        );
        return rows.length > 0;
    }
}

module.exports = new LinkController()